package cc.rboot.convert.helper;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.ArrayList;
import java.util.List;

public class ConvertHelper {
    public static <T, S> T convertTo(Class<T> clazz, S object) {
        return JSONObject.parseObject(JSONObject.toJSONString(object), clazz);
    }

    public static <T, S> T convert(T that, S object) {
        return (T) convertTo(that.getClass(), object);
    }

    public static <T, S> IPage<T> convert(T that, IPage<S> page) {
        Page<T> resultPage = convertTo(Page.class, page);

        List<T> recordList = new ArrayList<>();
        for (S record : page.getRecords()) {
            recordList.add(ConvertHelper.convert(that, record));
        }
        resultPage.setRecords(recordList);
        return resultPage;
    }

    public static <T, S> List<T> convert(T that, List<S> list) {
        List<T> recordList = new ArrayList<>();
        for (S record : list) {
            recordList.add(ConvertHelper.convert(that, record));
        }
        return recordList;
    }
}
